package com.arpa.wms.service.impl;

import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.CommonUtil;
import com.arpa.wms.domain.dto.CountingRegisterDTO;
import com.arpa.wms.domain.entity.CountingRegister;
import com.arpa.wms.domain.vo.CountingRegisterVO;
import com.arpa.wms.mapper.CountingRegisterMapper;
import com.arpa.wms.service.ICountingRegisterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 领用单明细 服务实现类
 * @author jinss
 * @date 2020-08-20 14:30:42
 **/
@Service
@Log4j2
public class CountingRegisterServiceImpl extends ServiceImpl<CountingRegisterMapper, CountingRegister> implements ICountingRegisterService {


    /**
     * 查询合计,包含总数
     *
     * @param countingRegisterDTO
     * @return
     */
    @Override
    public CountingRegisterVO queryListSum(CountingRegisterDTO countingRegisterDTO) {
        CountingRegisterVO countingRegisterVO = baseMapper.queryListSum(countingRegisterDTO);
        return countingRegisterVO;
    }

    @Override
    public List<CountingRegisterVO> queryList(CountingRegisterDTO countingRegisterDTO) {
        //排序字段名需要驼峰转数据库下划线类型字段名
        if(StringUtils.isNotEmpty(countingRegisterDTO.getSortField())){
            countingRegisterDTO.setSortField(CommonUtil.camel2Underline(countingRegisterDTO.getSortField()));
        }
        List<CountingRegisterVO> countingItemList = baseMapper.queryList(countingRegisterDTO);
        return countingItemList;
    }

    @Override
    public List<CountingRegisterVO> queryTaskDoneByCountCode(CountingRegisterDTO countingRegisterDTO) {
        return baseMapper.queryTaskDoneByCountCode(countingRegisterDTO);
    }

    /**
     * 盘点单完成检查确认
     * @param countingRegisterDTO
     * @return
     */
    @Override
    public boolean checkConfirm(CountingRegisterDTO countingRegisterDTO) {
        //统计盘点数量
        CountingRegisterVO countingRegisterVO = baseMapper.checkConfirm(countingRegisterDTO);
        if(null == countingRegisterVO){
            log.error("找不到盘点单【{}】盘点登记信息", countingRegisterDTO.getCountingCode());
            throw new ServiceException("找不到盘点单【"+countingRegisterDTO.getCountingCode()+"】盘点登记信息");
        }
        return countingRegisterVO.getInventoryQuantity().compareTo(countingRegisterVO.getCountingQuantity().add(countingRegisterVO.getStockQuantity())) == 0;
    }

    /**
     * 通过查询记录创建盘点登记明细
     *
     * @param countingCode 盘点单号
     * @param userCode     操作人code
     */
    @Override
    public void insertBatch(String countingCode, String userCode) {
        baseMapper.insertBatch(countingCode);
    }

}
